package org.dromara.workflow.rocketmq.leave;

import cn.hutool.core.util.ObjectUtil;
import com.cloud.rocketmq.base.entity.CloudMessage;
import com.cloud.rocketmq.spring.annotation.ConsumeTopic;
import com.cloud.rocketmq.spring.core.TopicListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.workflow.api.event.ProcessDeleteEvent;
import org.dromara.workflow.domain.TestLeave;
import org.dromara.workflow.mapper.TestLeaveMapper;

import static org.dromara.common.core.constant.RocketMQConstants.FlowTopic.*;

/**
 * 监听删除流程事件
 * 正常使用只需#processDeleteEvent.flowCode=='leave1'
 * 示例为了方便则使用startsWith匹配了全部示例key
 */
@Slf4j
@ConsumeTopic(topic = FLOW_PROCESS_TOPIC_NAME, eventCode = FLOW_PROCESS_DELETE_TAG_NAME, log = true)
@RequiredArgsConstructor
public class ProcessDeleteListener implements TopicListener<ProcessDeleteEvent> {

    private final TestLeaveMapper testLeaveMapper;

    @Override
    public void onMessage(CloudMessage<ProcessDeleteEvent> processDeleteMessage) {
        log.info("监听删除流程消息:{}", JsonUtils.toJsonString(processDeleteMessage));
        ProcessDeleteEvent processDeleteEvent = processDeleteMessage.getPayload();
        if (processDeleteEvent.getFlowCode().startsWith("leave")) {
            TenantHelper.dynamic(processDeleteEvent.getTenantId(), () -> {
                log.info("监听删除流程事件，当前任务执行了{}", processDeleteEvent);
                TestLeave testLeave = testLeaveMapper.selectById(Long.valueOf(processDeleteEvent.getBusinessId()));
                if (ObjectUtil.isNull(testLeave)) {
                    return;
                }
                testLeaveMapper.deleteById(testLeave.getId());
            });
        }
    }

}
